package com.geekaca.news.controller.admin;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.serialize.JSONArraySerializer;
import com.geekaca.news.domain.AdminUser;
import com.geekaca.news.domain.NewsCategory;
import com.geekaca.news.service.*;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 后台管理员用户的相关操作
 *
 * @Controller 接口返回值，Spring会解析，去找对应的页面
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private TagService tagService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private JedisPool jedisPool;


    //要访问thymeleaf制作的页面时候，要首先先访问控制器，
    //然后由控制器帮咱们跳转到页面，不能直接访问页面
    @GetMapping("/login")
    public String login() {
        //指向页面
        return "admin/login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(@RequestParam("userName") String userName,
                          @RequestParam("password") String password,
                          @RequestParam("verifyCode") String verifyCode,
                          HttpSession session) {
        /**
         *
         * 1，验证输入信息是否为空
         *    如果为空 ，要在session中保存错误信息，返回登录页
         * 2，调用service 验证登陆
         *      登陆成功 跳转页面进入后台首页
         *      return "redirect:/admin/index";
         */

        if (userName == null || "".equals(userName.trim())) {
            session.setAttribute("errorMsg", "用户名不能为空");
            return "redirect:admin/login";
        }


        if (password == null || "".equals(password.trim())) {
            session.setAttribute("errorMsg", "密码不能为空");
            return "redirect:admin/login";
        }

        if (verifyCode == null || "".equals(verifyCode.trim())) {
            session.setAttribute("errorMsg", "验证码不能为空");
            return "redirect:admin/login";
        }
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(password)) {
            session.setAttribute("errorMsg", "用户名或密码不能为空");
            return "admin/login";
        }
        if (!StringUtils.hasText(verifyCode)) {
            session.setAttribute("errorMsg", "验证码不能为空");
            return "admin/login";
        }


//        ShearCaptcha verifyCode1 = (ShearCaptcha) session.getAttribute("verifyCode");
//        if (!verifyCode.equals(verifyCode1.getCode())) {
//            //如果用户输入的验证码，和之前生成后保存的 不一致
//            session.setAttribute("errorMsg", "验证码错误");
//            return "redirect:admin/login";
//        }
        System.out.println("future a");
        System.out.println("future b");
        AdminUser adminUser = new AdminUser();
        adminUser.setLoginUserName(userName);
        adminUser.setLoginPassword(SecureUtil.md5(password));
        AdminUser loginUser = adminUserService.login(adminUser);

        System.out.println("loginUser :" + loginUser);
        if (loginUser != null) {
            //登陆成功
            System.out.println("登陆成功");
            session.setAttribute("loginUser", loginUser.getNickName());
            session.setAttribute("loginUserId", loginUser.getAdminUserId());
            session.setAttribute("loginUserName", loginUser.getLoginUserName());
            /**
             * 用户信息存入redis
             */
            Jedis jedis = jedisPool.getResource();
            String key = "uInfo:" + loginUser.getAdminUserId();
            HashMap<String, String> map = new HashMap<>();
            map.put("loginName", loginUser.getLoginUserName());
            map.put("nick", loginUser.getNickName());
            jedis.hmset(key, map);

            // 缓存类别
            List<NewsCategory> allCategories = categoryService.getAllCategories(null, null);
            Gson gson = new Gson();
            allCategories.forEach(category -> {
                jedis.lpush("categoryList", gson.toJson(category));
            });


            jedis.close();



            return "admin/index";
        } else {
            session.setAttribute("errorMsg", "登陆失败");
            return "admin/login";
        }
    }

    @GetMapping("/userInfo/{userid}")
    @ResponseBody
    public AdminUser getUserInfo(@PathVariable("userid") Integer uid) {
        Jedis jedis = jedisPool.getResource();
        Map<String, String> userMap = jedis.hgetAll("uInfo:" + uid);
        String loginName = userMap.get("loginName");
        String  nick= userMap.get("nick");
        AdminUser user = new AdminUser();
        user.setAdminUserId(uid);
        user.setNickName(nick);
        user.setLoginUserName(loginName);
        System.out.println("收到请求---------");
        return user;

    }


    @GetMapping({"", "/", "/index", "/index.html"})
    public String index(HttpServletRequest request) {
        request.setAttribute("path", "index");
        //类别数量  ctrl  + Alt 鼠标左键点击，跳转到函数实现
        //todo: 文章类别数量  单独的一个查询
        request.setAttribute("categoryCount", categoryService.getTotalCategories());
        //新闻总数
        request.setAttribute("blogCount", newsService.getTotalNews());
        //链接总数
        request.setAttribute("linkCount", linkService.getTotalLinks());
        //标签总数
        request.setAttribute("tagCount", tagService.getTotalTags());
        //评论总数
        request.setAttribute("commentCount", commentService.getTotalComments());
        return "admin/index";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "admin/login";
    }

}
